<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Menus extends CI_Controller {
    /* PAGES */

    /**
     * Constructeur de la class Menus
     */
    public function __construct() {
        parent::__construct();
        
        $this->acl->setModule('menus');
    }

    /**
     * Page d'administration des menus.
     */
    public function admin() {
        $this->acl->can('manage');

        $crud = new grocery_CRUD();

        $crud->set_table('S_INTRANET.V_MENU_MNU')
                ->set_subject('un menu')

                // Champs.
                ->columns('MNU_NAME')
                ->fields('MNU_NAME')
                ->required_fields('MNU_NAME')

                // Affichage.
                ->display_as('MNU_NAME', 'Nom')

                //actions.
                ->add_action('Liens', img_url('menus/links.png'), 'menus/adminLinks')
                ->add_action('Descendre', img_url('menus/down.png'), '', 'menuDown disable', array($this, 'callbackMenuActionDown'))
                ->add_action('Monter', img_url('menus/up.png'), '', 'menuUp disable', array($this, 'callbackMenuActionUp'))
        ;
        $crud->order_by('MNU_POSITION', 'ASC');

        // Callbacks
        $crud->callback_delete(array($this, 'callbackMenuDelete'));
        $crud->callback_insert(array($this, 'callbackMenuInsert'));
        $crud->callback_update(array($this, 'callbackMenuUpdate'));

        $this->db = $this->load->database('DB_PLASTPROD', true);
        $output = $crud->render();

        $css = $crud->get_css_files();
        $js = $crud->get_js_files();

        if (isset($js['e9e289fc80d543c348f4e70ca9d893d32bd5dfbf']))
            unset($js['e9e289fc80d543c348f4e70ca9d893d32bd5dfbf']);

        $this->layout
                ->setTitle('Menus')
                ->setCss($css)
                ->setJs($js)
                ->setJs('menu')
                ->view('menus/admin', $output)
                ->display()
        ;
    }

    /**
     * Page d'administration des liens d'un menu.
     * 
     * @param   int     $menu
     */
    public function adminLinks($menu) {
        $this->acl->can('manage');

        $crud = new grocery_CRUD();

        $crud->set_table('S_INTRANET.V_LINK_LNK')
                ->set_subject('un lien')

                // Champs.
                ->columns('LNK_NAME', 'LNK_LINK')
                ->fields('LNK_NAME', 'LNK_LINK', 'MNU_ID', 'GROUPS')
                ->required_fields('LNK_NAME', 'LNK_LINK')

                // Affichage.
                ->display_as('GROUPS', 'Groupes')
                ->display_as('LNK_LINK', 'Lien')
                ->display_as('LNK_NAME', 'Nom')

                // CHamgement des champs
                ->field_type('MNU_ID', 'hidden', $menu)

                // Relations.
                ->set_relation_n_n('GROUPS', 'S_INTRANET.T_J_LINK_GROUP_LKG', 'S_INTRANET.V_GROUP_GRP', 'LNK_ID', 'GRP_ID', '{GRP_NAME}', 'LKG_ID')

                //actions.
                ->add_action('Descendre', img_url('menus/down.png'), '', 'linkDown disable', array($this, 'callbackLinkActionDown'))
                ->add_action('Monter', img_url('menus/up.png'), '', 'linkUp disable', array($this, 'callbackLinkActionUp'))
        ;

        $crud->where('MNU_ID', $menu);
        $crud->order_by('LNK_POSITION', 'ASC');

        // Callbacks
        $crud->callback_delete(array($this, 'callbackLinkDelete'));
        $crud->callback_insert(array($this, 'callbackLinkInsert'));
        $crud->callback_update(array($this, 'callbackLinkUpdate'));

        $this->db = $this->load->database('DB_PLASTPROD', true);
        $output = $crud->render();

        $css = $crud->get_css_files();
        $js = $crud->get_js_files();

        if (isset($js['e9e289fc80d543c348f4e70ca9d893d32bd5dfbf']))
            unset($js['e9e289fc80d543c348f4e70ca9d893d32bd5dfbf']);

        $this->layout
                ->setTitle('Liens')
                ->setCss($css)
                ->setJs($js)
                ->setJs('menu')
                ->view('menus/adminLinks', $output)
                ->display()
        ;
    }

    /* ASYNCHRONE */

    /**
     * Descend le lien.
     * 
     * @param   int     $id
     */
    public function linkDown($id) {
        if ($this->acl->can('manage', false)) {
            $datas = array(
                $id
            );

            $result = callProc('DB_PLASTPROD', 'S_INTRANET', 'P_U_LINK_DOWN_00', $datas);

            if ('SUCCESS' === $result->RESULT)
                $toReturn = array(
                    'result' => 'success',
                    'message' => 'Le lien a été descendu.'
                );
            else
                $toReturn = array(
                    'result' => 'error',
                    'message' => 'Une erreur est survenue lors du déplacement du lien.'
                );
        }

        else {
            $toReturn = array(
                'result' => 'error',
                'message' => 'Vous ne disposez pas des droits pour déplacer le lien.'
            );
        }

        echo json_encode($toReturn);
    }

    /**
     * Monte le lien.
     * 
     * @param   int     $id
     */
    public function linkUp($id) {
        if ($this->acl->can('manage', false)) {
            $datas = array(
                $id
            );

            $result = callProc('DB_PLASTPROD', 'S_INTRANET', 'P_U_LINK_UP_00', $datas);

            if ('SUCCESS' === $result->RESULT)
                $toReturn = array(
                    'result' => 'success',
                    'message' => 'Le lien a été monté.'
                );
            else
                $toReturn = array(
                    'result' => 'error',
                    'message' => 'Une erreur est survenue lors du déplacement du lien.'
                );
        }

        else {
            $toReturn = array(
                'result' => 'error',
                'message' => 'Vous ne disposez pas des droits pour déplacer le lien.'
            );
        }

        echo json_encode($toReturn);
    }

    /**
     * Descend le menu.
     * 
     * @param   int     $id
     */
    public function menuDown($id) {
        if ($this->acl->can('manage', false)) {
            $datas = array(
                $id
            );

            $result = callProc('DB_PLASTPROD', 'S_INTRANET', 'P_U_MENU_DOWN_00', $datas);

            if ('SUCCESS' === $result->RESULT)
                $toReturn = array(
                    'result' => 'success',
                    'message' => 'Le menu a été descendu.'
                );
            else
                $toReturn = array(
                    'result' => 'error',
                    'message' => 'Une erreur est survenue lors du déplacement du menu.  '
                );
        }

        else {
            $toReturn = array(
                'result' => 'error',
                'message' => 'Vous ne disposez pas des droits pour déplacer le menu.'
            );
        }

        echo json_encode($toReturn);
    }

    /**
     * Monte le menu.
     * 
     * @param   int     $id
     */
    public function menuUp($id) {
        if ($this->acl->can('manage', false)) {
            $datas = array(
                $id
            );

            $result = callProc('DB_PLASTPROD', 'S_INTRANET', 'P_U_MENU_UP_00', $datas);

            if ('SUCCESS' === $result->RESULT)
                $toReturn = array(
                    'result' => 'success',
                    'message' => 'Le menu a été monté.'
                );
            else
                $toReturn = array(
                    'result' => 'error',
                    'message' => 'Une erreur est survenue lors du déplacement du menu.  '
                );
        }

        else {
            $toReturn = array(
                'result' => 'error',
                'message' => 'Vous ne disposez pas des droits pour déplacer le menu.'
            );
        }

        echo json_encode($toReturn);
    }

    /* CALLBACKS */

    /**
     * Callback d'affichage de l'action descendre le lien.
     * 
     * @param   int         $id
     * @param   stdClass    $row
     * @return  string
     */
    public function callbackLinkActionDown($id) {
        $request = 'SELECT "DB_PLASTPROD"."S_INTRANET"."F_LINK_IS_ON_MAX"(' . $id . ') AS "IS_ON_MAX"';

        $CI = get_instance();
        $CI->db = $CI->load->database('DB_PLASTPROD', true);
        $tmp = $CI->db->query($request)->result();

        if ('f' === $tmp[0]->IS_ON_MAX)
            return $id;
        return 'disable';
    }

    /**
     * Callback d'affichage de l'action monter le lien.
     * 
     * @param   int         $id
     * @param   stdClass    $row
     * @return  string
     */
    public function callbackLinkActionUp($id) {
        $request = 'SELECT "DB_PLASTPROD"."S_INTRANET"."F_LINK_IS_ON_MIN"(' . $id . ') AS "IS_ON_MIN"';

        $CI = get_instance();
        $CI->db = $CI->load->database('DB_PLASTPROD', true);
        $tmp = $CI->db->query($request)->result();

        if ('f' === $tmp[0]->IS_ON_MIN)
            return $id;
        return 'disable';
    }

    /**
     * Callback de suppression d'un lien.
     * 
     * @param   int     $id
     * @return  boolean
     */
    public function callbackLinkDelete($id) {
        if ($this->acl->can('manage', false)) {
            $datas = array(
                $id
            );

            $result = callProc('DB_PLASTPROD', 'S_INTRANET', 'P_D_LINK_00', $datas);

            if ('SUCCESS' === $result->RESULT)
                return true;
        }
        return false;
    }

    /**
     * Callback de création d'un lien.
     * 
     * @param   array   $post
     * @return  boolean
     */
    public function callbackLinkInsert($post) {
        if ($this->acl->can('manage', false)) {
            $datas = array(
                $post['MNU_ID'],
                '\'' . pg_escape_string($post['LNK_NAME']) . '\'',
                '\'' . pg_escape_string($post['LNK_LINK']) . '\''
            );

            $result = callProc('DB_PLASTPROD', 'S_INTRANET', 'P_I_LINK_00', $datas);

            if ('SUCCESS' === $result->RESULT) {
                // Si il y a des utilisateurs à ajouter.
                if (isset($post['GROUPS'])) {
                    foreach ($post['GROUPS'] AS $group) {
                        $datas = array(
                            $result->MESSAGE,
                            $group
                        );
                        callProc('DB_PLASTPROD', 'S_INTRANET', 'P_I_LINK_GROUP_00', $datas);
                    }
                }

                return true;
            }
        }
        return false;
    }

    /**
     * Callback de mise à jour d'un lien.
     * 
     * @param   array   $post
     * @param   int     $id
     * @return  boolean
     */
    public function callbackLinkUpdate($post, $id) {
        if ($this->acl->can('manage', false)) {
            $datas = array(
                $id,
                '\'' . pg_escape_string($post['LNK_NAME']) . '\'',
                '\'' . pg_escape_string($post['LNK_LINK']) . '\''
            );

            $result = callProc('DB_PLASTPROD', 'S_INTRANET', 'P_U_LINK_00', $datas);

            if ('SUCCESS' === $result->RESULT) {
                $tmp = $this->db
                        ->select('*')
                        ->from('"S_INTRANET"."P_S_LINK_GROUP_BY_LINK_00"(' . $id . ')')
                        ->get()
                        ->result()
                ;
                $groupsInLink = array();
                foreach ($tmp AS $group)
                    array_push($groupsInLink, $group->GRP_ID);

                if (!isset($post['USERS']))
                    $post['USERS'] = array();

                // On retire les groupes a retirer.
                foreach ($groupsInLink AS $group) {
                    if (!in_array($group, $post['GROUPS'])) {
                        $datas = array(
                            $id,
                            $group
                        );
                        callProc('DB_PLASTPROD', 'S_INTRANET', 'P_D_LINK_GROUP_00', $datas);
                    }
                }

                // On ajoute les groupes.
                foreach ($post['GROUPS'] AS $group) {
                    if (!in_array($user, $groupsInLink)) {
                        $datas = array(
                            $id,
                            $group
                        );
                        callProc('DB_PLASTPROD', 'S_INTRANET', 'P_I_LINK_GROUP_00', $datas);
                    }
                }

                return true;
            }
        }
        return false;
    }

    /**
     * Callback d'affichage de l'action descendre le menu.
     * 
     * @param   int         $id
     * @param   stdClass    $row
     * @return  string
     */
    public function callbackMenuActionDown($id) {
        $request = 'SELECT "DB_PLASTPROD"."S_INTRANET"."F_MENU_IS_ON_MAX"(' . $id . ') AS "IS_ON_MAX"';

        $CI = get_instance();
        $CI->db = $CI->load->database('DB_PLASTPROD', true);
        $tmp = $CI->db->query($request)->result();

        if ('f' === $tmp[0]->IS_ON_MAX)
            return $id;
        return 'disable';
    }

    /**
     * Callback d'affichage de l'action monter le menu.
     * 
     * @param   int         $id
     * @param   stdClass    $row
     * @return  string
     */
    public function callbackMenuActionUp($id) {
        $request = 'SELECT "DB_PLASTPROD"."S_INTRANET"."F_MENU_IS_ON_MIN"(' . $id . ') AS "IS_ON_MIN"';

        $CI = get_instance();
        $CI->db = $CI->load->database('DB_PLASTPROD', true);
        $tmp = $CI->db->query($request)->result();

        if ('f' === $tmp[0]->IS_ON_MIN)
            return $id;
        return 'disable';
    }

    /**
     * Callback de suppression d'un menu.
     * 
     * @param   int     $id
     * @return  boolean
     */
    public function callbackMenuDelete($id) {
        if ($this->acl->can('manage', false)) {
            $datas = array(
                $id
            );

            $result = callProc('DB_PLASTPROD', 'S_INTRANET', 'P_D_MENU_00', $datas);

            if ('SUCCESS' === $result->RESULT)
                return true;
        }
        return false;
    }

    /**
     * Callback de création d'un menu.
     * 
     * @param   array   $post
     * @return  boolean
     */
    public function callbackMenuInsert($post) {
        if ($this->acl->can('manage', false)) {
            $datas = array(
                '\'' . pg_escape_string($post['MNU_NAME']) . '\''
            );

            $result = callProc('DB_PLASTPROD', 'S_INTRANET', 'P_I_MENU_00', $datas);

            if ('SUCCESS' === $result->RESULT)
                return true;
        }
        return false;
    }

    /**
     * Callback de mise à jour d'un menu.
     * 
     * @param   array   $post
     * @param   int     $id
     * @return  boolean
     */
    public function callbackMenuUpdate($post, $id) {
        if ($this->acl->can('manage', false)) {
            $datas = array(
                $id,
                '\'' . pg_escape_string($post['MNU_NAME']) . '\''
            );

            $result = callProc('DB_PLASTPROD', 'S_INTRANET', 'P_U_MENU_00', $datas);

            if ('SUCCESS' === $result->RESULT)
                return true;
        }
        return false;
    }

}